package com.unisyou.filter;

import com.unisyou.config.PropertiesConfig;
import com.unisyou.utils.CookieUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SecurityInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private PropertiesConfig propertiesConfig;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        String token = "";
        String mobile = CookieUtil.get(request,"mobile")!=null?CookieUtil.get(request,"mobile").getValue():"";
        String requestToken = CookieUtil.get(request,"token")!=null?CookieUtil.get(request,"token").getValue():"";
        if(!StringUtils.isBlank(mobile)){
            token = stringRedisTemplate.opsForValue().get(mobile);
        }
        if (!StringUtils.isBlank(requestToken) && requestToken.equals(token)) {
            return true;
        }
        String url = propertiesConfig.getLoginUri();
        response.sendRedirect(url);
        return false;
    }
}